package com.z.redis.datatype;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * Redis 核心数据封装类
 * @author zxb
 */
public class BytesWrapper implements Comparable<BytesWrapper> {
    //封装字节数组 实现二进制安全的数据操作
    static final Charset CHARSET = StandardCharsets.UTF_8;
    private final byte[] content;//存储二进制数据的不可变字节数组

    public BytesWrapper(byte[] content) {
        this.content = Arrays.copyOf(content,content.length);
    }
    public byte[] getByteArray() {
        return Arrays.copyOf(content,content.length);
    }
    @Override
    public boolean equals(Object o){
        if(this == o) return true;//同一类型直接返回
        if(o == null || getClass() != o.getClass()) return false;//类型检查
        BytesWrapper that = (BytesWrapper) o;
        return Arrays.equals(content, that.content);
    }
    public String toUTF8String() { return new String(content,CHARSET);}
    @Override
    public int hashCode(){return Arrays.hashCode(content);}
    @Override
    public int compareTo(BytesWrapper o){
        byte[] v1=this.content;
        byte[] v2=o.content;
        int minLen=Math.min(v1.length,v2.length);
        for(int i=0;i<minLen;i++){
            int b1=Byte.toUnsignedInt(v1[i]);
            int b2=Byte.toUnsignedInt(v2[i]);
            if(b1 != b2) return Integer.compare(b1,b2);
        }
        return Integer.compare(v1.length,v2.length);
    }
}
